<?php
namespace app\swoole\controller;

use think\Controller;

class Index extends Controller
{
	/**
	 * 连接端口
	 * @var unknown
	 */
	private $port = '1235';
	/**
	 * 请求ip
	 * @var unknown
	 */
	private $ip = '0.0.0.0';
	
	/**
	 * 实例化swoole对象
	 * @var unknown
	 */
	private $ws;
	
    public function index()
    {
    	//实例化swoole的websocket对象
    	$this->ws = new \swoole_websocket_server($this->ip, $this->port);
    	//监听打开
    	$this->ws->on('open',function($ws, $request){
    		$this->wsOpen($ws, $request);
    	});
    	//监听消息推送
    	$this->ws->on('message',function($ws, $frame){
    		$this->wsMessage($ws, $frame);
    	});
    	//监听客户端关闭事件
    	$this->ws->on('close',function($ws, $fd){
    		$this->wsClose($ws, $fd);
    	});
    	//启动swoole
    	$this->ws->start();
    }
    
    /**
     * swoole 连接事件
     * @param unknown $ws
     * @param unknown $request
     */
    private function wsOpen($ws, $request)
    {
    }
    
    /**
     * 监听WebSocket消息事件
     * @param unknown $ws
     * @param unknown $frame
     */
    private function wsMessage($ws, $frame)
    {
    	dump($frame->data);
    	dump($frame->fd);
    	$this->ws->push($frame->fd,$frame->data);
    }
    
    /**
     * 监听WebSocket连接关闭事件
     * @param unknown $ws
     * @param unknown $fd
     */
    private function wsClose($ws, $fd)
    {
    }
}
